<?php
namespace admin\action;

use api\utils\MpeApiClient;
use herosphp\bean\Beans;
use herosphp\core\Log;
use herosphp\http\HttpRequest;
use herosphp\string\StringUtils;
use herosphp\utils\AjaxResult;
use herosphp\utils\ArrayUtils;

/**
 * user action
 * @package admin\action
 * @author yangjian<yangjian102621@gmail.com>
 */
class UserAction extends CommonAction {

    protected $serviceBean = 'user.user.service';
    protected $actionTitle = '大塑账户';

    //数据列表页面
    public function index( HttpRequest $request ) {
        $username = $request->getParameter('username', 'trim');
        $name = $request->getParameter('name', 'trim');
        $sign_status = $request->getParameter('sign_status', 'trim');
        $starttime = $request->getParameter('starttime', 'trim');
        $endtime = $request->getParameter('endtime', 'trim');
        if ( $sign_status === '' ) {
            $sign_status = '-1';
            $request->addParameter('sign_status', '-1');
        }

        $conditions = array();
        if ( $username ) $conditions['username'] = "%{$username}%";
        if ( $name ) $conditions['contacter'] = "%{$name}%";
        if ( $sign_status != '-1' ) $conditions['sign_status'] = $sign_status;
        if ( $starttime ) $conditions['addtime']['>'] = $starttime.' 00:00:00';
        if ( $endtime ) $conditions['addtime']['<'] = $endtime.' 24:00:00';

        $this->setConditions($conditions);
        parent::index($request);
        $this->getAllManagers();
        $this->loadPayways();
        $this->loadBanks();
        $this->assign('signStatus', array('0' => '未签约', '1' => '已签约', '2' => '已解约'));

        $this->assign('tableHeader', array('会员号', '会员类型','联系人','实名认证','签约状态','会员状态','认证时间','注册时间'));
        $this->export($request); //导出数据

        $this->setView('user/user_index');
        $this->assign('breadcrumb', array('大塑账户', '会员列表'));
    }

    //已签约会员列表
    public function signlist(HttpRequest $request) {

        $username = $request->getParameter('username', 'trim');
        $name = $request->getParameter('contacter', 'trim');
        $bank_id = $request->getParameter('bank_id', 'trim');
        $starttime = $request->getParameter('starttime', 'trim');
        $endtime = $request->getParameter('endtime', 'trim');
        if ( $bank_id === '' ) {
            $bank_id = '-1';
            $request->addParameter('bank_id', '-1');
        }

        $conditions = array("sign_status" => 1);
        if ( $username ) $conditions['username'] = "%{$username}%";
        if ( $name ) $conditions['contacter'] = "%{$name}%";
        if ( $bank_id != '-1' ) $conditions['sign_bank_id'] = $bank_id;
        if ( $starttime ) $conditions['sign_time']['>'] = $starttime.' 00:00:00';
        if ( $endtime ) $conditions['sign_time']['<'] = $endtime.' 24:00:00';

        $this->setConditions($conditions);
        $this->loadBanks();
        $this->loadPayways();

        $this->assign('tableHeader', array('会员号','联系人','支付通道','签约银行','银行网点','户名','银行卡号','附属帐号','签约时间'));
        if ( $request->getParameter('__export') == 1 ) {
            $this->export($request); //导出数据

        } else { //加载视图显示数据
            parent::index($request);
            $this->setView('user/sign_list');
            $this->assign('breadcrumb', array('大塑账户', '签约列表'));
        }

    }

    //数据添加页面
    public function add(HttpRequest $request) {
        $this->setView('user/user_add');
        $this->assign('breadcrumb', array('大塑账户', '会员注册'));
    }

    //加载支付通道
    protected function loadPayways() {
        $service = Beans::get('payment.payway.service');
        $payways = $service->getItems(array('status' => 1));
        $payways = ArrayUtils::changeArrayKey($payways, 'id');
        $this->assign('payways', $payways);
    }

    //加载银行
    protected function loadBanks() {
        $service = Beans::get('payment.bank.service');
        $banks = $service->getItems(array('status' => 1));
        $banks = ArrayUtils::changeArrayKey($banks, 'id');
        $this->assign('banks', $banks);
    }

    //数据编辑页面
    public function edit(HttpRequest $request) {
        $id = $request->getParameter('id', 'trim');
        if ( empty($id) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        $userService = Beans::get($this->serviceBean);
        $companyService = Beans::get('user.company.service');
        $item = $userService->getItem($id);
        $company = $companyService->getItem(array('userid' => $id));
        $company['main_business'] = StringUtils::jsonDecode($company['main_business']);
        if ( !$company['main_business'] ) {
            $company['main_business'] = array();
        }
        $this->assign('item', $item);
        $this->assign('company', $company);

        if ( $item['type'] == 1 ) {
            $this->setView('user/person_user_edit');
        } else {
            $this->setView('user/company_user_edit');
        }
        $this->assign('breadcrumb', array('大塑账户', '会员编辑'));
    }

    //插入数据操作
    public function insert(HttpRequest $request) {

        $data = $request->getParameter('data');
        $data['id'] = StringUtils::genGlobalUid(false, 24);

        $data['addtime'] = date('Y-m-d H:i:s');
        $data['updatetime'] = date('Y-m-d H:i:s');
        $data['password'] = md5(md5($data['password']));
        $data['ischecked'] = 1; //后台添加的会员默认都所在审核中(不用申请审核这个动作)

        $userService = Beans::get($this->serviceBean);
        $companyService = Beans::get('user.company.service');
        //1. 个人用户注册
        if ( $data['type'] == 1 ) {
            if ( $userService->add($data) == false ) {
                AjaxResult::ajaxFailtureResult();
            }

        } else if ( $data['type'] == 2 ) { //2.企业用户
            $userService->beginTransaction();
            if ( $userService->add($data) == false ) {
                $userService->rollback();
                AjaxResult::ajaxFailtureResult();
            }

            //添加公司信息
            $company = $request->getParameter('company');
            $company['userid'] = $data['id'];
            $company['main_business'] = StringUtils::jsonEncode($request->getParameter('main_business'));
            $company['addtime'] = $data['addtime'];
            $company['updatetime'] = $data['updatetime'];
            $company['register_capital'] = floatval($company['register_capital']);

            if ( $companyService->add($company) == false ) {
                $userService->rollback();
                AjaxResult::ajaxFailtureResult();
            }
            $userService->commit(); //提交事务
        }

        //添加操作日志
        $request->addParameter('logmessage', "添加用户[{$data['username']}]");

        AjaxResult::ajaxSuccessResult();  //操作成功

    }

    //更新数据操作
    public function update(HttpRequest $request) {

        $id = $request->getParameter('id', 'trim');
        $data = $request->getParameter('data');
        $company = $request->getParameter('company');

        $data['updatetime'] = date('Y-m-d H:i:s');
        $userService = Beans::get($this->serviceBean);
        $item = $userService->getItem($id);
        if($item && $item['ischecked'] == 0){
            $data['ischecked'] = 1;
        }
        $result = $userService->update($data, $id);
        if ( $result == false ) {
            AjaxResult::ajaxFailtureResult();
        }
        if ( !empty($company) ) {  //企业用户需要更新公司信息
            $company['main_business'] = StringUtils::jsonEncode($request->getParameter('main_business'));
            $company['updatetime'] = $data['updatetime'];
            $companyService = Beans::get('user.company.service');
            $companyService->update($company, $id);

            //如果更新了公司名称应该同步更新MPE的实名认证公司信息
            $company_bak = $request->getParameter('company_bak', 'trim');
            if ( $company['company'] != $company_bak ) {
                $__data = array(
                    'real_name' => $company['company']
                );
                $res = MpeApiClient::send('api/memberApi/updateMember', array('data' => $__data, 'userid' => $id));
                if ( !$res->isSucess() ) {
                    Log::info("同步实名认证信息失败， 公司名称：{$company['company']}, userid : {$id}");
                }else{
                    $res = MpeApiClient::send('api/memberApi/updateSessionApi', array('userid' => $id,'key' => 'dasuinfo'));
                    if ( !$res->isSucess() ) {
                        Log::info("更新MPE Session信息失败,接口返回：".$res->getMessage());
                    }
                }
            }
        }
        AjaxResult::ajaxSuccessResult();

    }

    //修改会员名
    public function modifyMobile(HttpRequest $request) {
        $id = $request->getParameter('id', 'trim');
        $username = $request->getParameter('username', 'trim');
        if ( empty($id) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        $oldUser = $this->getOptobjById($id);
        $service = Beans::get($this->getServiceBean());
        if ( $service->count(array('username' => $username)) > 0 ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "会员名 {$username} 已经存在.");
        }
        if ( $service->set('username', $username, $id) ) {
            //添加操作日志
            $request->addParameter('logmessage', "更改[{$oldUser}]会员号为[{$username}]");
            AjaxResult::ajaxSuccessResult();
        } else {
            AjaxResult::ajaxFailtureResult();
        }

    }

    //修改密码
    public function modifyPass(HttpRequest $request) {
        $id = $request->getParameter('id', 'trim');
        $password = $request->getParameter('password', 'trim');
        if ( empty($id) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        $service = Beans::get($this->getServiceBean());
        if ( $service->set('password', md5(md5($password)), $id) ) {
            //添加操作日志
            $request->addParameter('logmessage', "更改[{$this->getOptobjById($id)}]会员的登录密码");
            AjaxResult::ajaxSuccessResult();
        } else {
            AjaxResult::ajaxFailtureResult();
        }
    }

    //用户认证审核
    public function check(HttpRequest $request) {

        $id = $request->getParameter('id', 'trim');
        if ( empty($id) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        $userService = Beans::get('user.user.service');
        $item = $userService->getItem($id);
        $this->assign('item', $item);
        $this->assign('company', $item['company']);
        if ( $item['type'] == 1 ) {
            $this->setView('user/person_user_check');
        } elseif ( $item['type'] == 2 ) {
            $this->setView('user/company_user_check');
        }
        $this->assign('breadcrumb', array('大塑账户', '会员审核'));
    }

    //用户认证审核操作
    public function doCheck(HttpRequest $request) {

        $id = $request->getParameter('id', 'trim');
        $userType = $request->getParameter('usertype', 'trim');

        if ( empty($id) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        $user = $request->getParameter('user');
        $company = $request->getParameter('company');

        $user['updatetime'] = date('Y-m-d H:i:s');
        $user['checktime'] = date('Y-m-d H:i:s');
        $user['checker'] = $this->loginUser->getId();
        if ( $user['ischecked'] == 2 ) { //审核成功, 则实名认证的名称作为虚拟账号开户名称
            if ( $userType == 1 ) {
                $user['virtual_name'] = $user['real_name'];
            } else {
                $user['virtual_name'] = $company['company'];
            }
        }

        $userService = Beans::get($this->getServiceBean());
        //1. 个人用户审核
        if ( $userType == 1 ) {
            if ( $userService->update($user, $id) == false ) {
                AjaxResult::ajaxFailtureResult();
            }

        } else { //2.企业用户实名认证审核

            $userService->beginTransaction();
            if ( $userService->update($user, $id) == false ) {
                $userService->rollback();
                AjaxResult::ajaxFailtureResult();
            }

            //更新企业认证信息
            $companyService = Beans::get('user.company.service');
            if ( $companyService->update($company, $id) == false ) {
                $userService->rollback();
                AjaxResult::ajaxFailtureResult();
            }
            $userService->commit();

            //如果审核通过则更新MPE端的用户信息
            if ( $user['ischecked'] == 2 ) {
                $data = array(
                    'ischecked' => 1,
                    'real_name' => $user['virtual_name']
                );
                $res = MpeApiClient::send('api/memberApi/updateMember', array('data' => $data, 'userid' => $id));
                if ( !$res->isSucess() ) {
                    Log::info("同步实名认证信息失败， real_name : {$user['virtual_name']}, userid : {$id}");
                }
            }else{//不通过就去更新MPE信息
                $res = MpeApiClient::send('api/memberApi/updateSessionApi', array('userid' => $id,'key' => 'dasuinfo'));
                if ( !$res->isSucess() ) {
                    Log::info("更新MPE Session信息失败,接口返回：".$res->getMessage());
                }
            }
        }

        AjaxResult::ajaxSuccessResult();

    }

    //签约银行
    public function signBank(HttpRequest $request) {
        $id = $request->getParameter('id', 'trim');
        if ( empty($id) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        $userService = Beans::get($this->serviceBean);
        $user = $userService->getItem($id);
        if ( $user ) {
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, '', $user);
        } else {
            AjaxResult::ajaxFailtureResult();
        }
    }

    //签约银行操作
    public function dosignBank(HttpRequest $request) {

        $id = $request->getParameter('id', 'trim');
        if ( empty($id) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        $data = $request->getParameter('data');
        $service = Beans::get($this->getServiceBean());
        if ( $service->signBank($id, $data) ) {
            //添加操作日志
            $request->addParameter('logmessage', "为大塑账户 [{$this->getOptobjById($id)}] 进行了银行签约操作");
            AjaxResult::ajaxSuccessResult();
        } else {
            AjaxResult::ajaxFailtureResult();
        }
    }

    //修改交易密码
    public function tradePass(HttpRequest $request) {
        $id = $request->getParameter('id', 'trim');
        $tradepass = $request->getParameter('tradepass', 'trim');
        if ( empty($id) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        $service = Beans::get($this->getServiceBean());
        if ( $service->set('tradepass', md5(md5($tradepass)), $id) ) {
            //添加操作日志
            $request->addParameter('logmessage', "修改大塑账户 [{$this->getOptobjById($id)}] 交易密码");
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, '交易密码修改成功.');
        } else {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '交易密码修改失败.');
        }
    }

    //银行解约
    public function unsignBank(HttpRequest $request) {

        $id = $request->getParameter('id', 'trim');
        if ( empty($id) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        $service = Beans::get($this->getServiceBean());
        if ( $service->unsignBank($id) ) {
            //添加操作日志
            $request->addParameter('logmessage', "为大塑账户 [{$this->getOptobjById($id)}] 进行了银行解约操作");
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, "解约成功.");
        } else {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '解约失败.');
        }
    }

    //导出数据
    protected function export(HttpRequest $request) {
        if( $request->getParameter('__export') == 1 ){
            $ids = $request->getParameter('ids');
            if( $ids ){
                $conditions['id']['$in']=$ids;
                $this->setConditions($conditions);
            }
            $this->setPagesize(getConfig('export_max_count'));
            $service = Beans::get($this->getServiceBean());
            $items = $service->where($this->getConditions())->limit(1, $this->getPagesize())->sort(array('addtime' => -1))->find();
            $excel = array();
            if ( $request->getMethod() == 'index' ) {
                foreach($items as $k => $v)
                {
                    $tmp = array();
                    $tmp[] = $v["username"];
                    $tmp[] = $v["type"] == 2 ? '企业' : '个人';
                    $tmp[] = $v["contacter"];
                    if ( $v['ischecked'] == 0 ) $tmp[] = '未申请';
                    if ( $v['ischecked'] == 1 ) $tmp[] = '未审核';
                    if ( $v['ischecked'] == 2 ) $tmp[] = '已通过';
                    if ( $v['ischecked'] == 3 ) $tmp[] = '未通过';

                    if ( $v['sign_status'] == 0 ) $tmp[] = '未签约';
                    if ( $v['sign_status'] == 1 ) $tmp[] = '已签约';
                    if ( $v['sign_status'] == 2 ) $tmp[] = '已解约';
                    $tmp[] = $v['status'] == 1 ? '启用' : '禁用';
                    $tmp[] = $v["checktime"];
                    $tmp[] = $v["addtime"];
                    $excel[] = $tmp;
                }
                $title = '大塑账户列表';

            } elseif ($request->getMethod() == 'signlist') {
                foreach($items as $k => $v)
                {
                    $tmp = array();
                    $tmp[] = $v["username"];
                    $tmp[] = $v["contacter"];
                    $payways = $this->getTemplateVar('payways');
                    $tmp[] = $payways[$v['payway']]['name'];
                    $banks = $this->getTemplateVar('banks');
                    $tmp[] = $banks[$v['sign_bank_id']]['name'];

                    $tmp[] = $v["sign_bank_branch"];
                    $tmp[] = $v["card_no"];
                    $tmp[] = $v["virtual_account"];
                    $tmp[] = $v["sign_time"];
                    $excel[] = $tmp;
                }
                $title = '签约列表';

            } elseif ($request->getMethod() == 'fund') {
                foreach($items as $k => $v)
                {
                    $tmp = array();
                    $tmp[] = $v["username"];
                    $tmp[] = $v["virtual_name"];
                    $banks = $this->getTemplateVar('banks');
                    $tmp[] = $banks[$v['sign_bank_id']]['name'];
                    $tmp[] = $v['virtual_account'];
                    $tmp[] = $v['usable'];
                    $tmp[] = $v['total_cost'];
                    $excel[] = $tmp;
                }
                $title = '资金统计';
            }
            $header = $this->getTemplateVar('tableHeader');
            phpexcel($title,$header,$excel);
            exit();
        }
    }

    //资金统计
    public function fund( HttpRequest $request ) {
        $username = $request->getParameter('username', 'trim');
        $virtual_name = $request->getParameter('virtual_name', 'trim');

        $conditions = array();
        $conditions['sign_status'] = 1;
        if ( $username ) $conditions['username'] = "%{$username}%";
        if ( $virtual_name ) $conditions['virtual_name'] = "%{$virtual_name}%";

        $this->setConditions($conditions);
        parent::index($request);
        $this->getAllManagers();
        $this->loadPayways();
        $this->loadBanks();
        $this->assign('signStatus', array('0' => '未签约', '1' => '已签约', '2' => '已解约'));

        $this->assign('tableHeader', array('大塑支付会员', '开户名','签约银行','附属账户','账户余额（￥）','累计消费（￥）','累计入金（￥）','累计出金（￥）','累计提现（￥）'));
        $this->export($request); //导出数据

        $this->setView('user/user_fund');
        $this->assign('breadcrumb', array('支付管理', '资金统计'));
    }
}
